package org.example.springboot.controller;

import org.example.springboot.entity.ExpertChat;
import org.example.springboot.repository.ExpertChatRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.example.springboot.entity.ExpertAppointment;
import org.example.springboot.entity.User;
import org.example.springboot.entity.Expert;
import org.example.springboot.repository.ExpertAppointmentRepository;
import org.example.springboot.service.UserService;
import org.example.springboot.service.ExpertService;
import java.util.Map;
import java.util.HashMap;

import java.util.Date;
import java.util.List;

/**
 * @author reisen7
 * @date 2025/5/30 13:10
 * @description 
 */

@RestController
@RequestMapping("/chat")
public class ChatController {

    @Autowired
    private ExpertChatRepository expertChatRepository;
    @Autowired
    private ExpertAppointmentRepository expertAppointmentRepository;
    @Autowired
    private UserService userService;
    @Autowired
    private ExpertService expertService;

    // 获取历史消息（userId, expertId）
    @GetMapping("/history")
    public List<ExpertChat> getHistory(
            @RequestParam Long userId,
            @RequestParam Long expertId
    ) {
        return expertChatRepository.findByUserIdAndExpertIdOrderBySendTimeAsc(userId, expertId);
    }

    // 获取所有相关历史消息（userId 或 expertId）
    @GetMapping("/history/all")
    public List<ExpertChat> getAllHistory(@RequestParam(required = false) Long userId,
                                          @RequestParam(required = false) Long expertId) {
        if (userId != null) {
            return expertChatRepository.findByUserIdOrderBySendTimeAsc(userId);
        } else if (expertId != null) {
            return expertChatRepository.findByExpertIdOrderBySendTimeAsc(expertId);
        } else {
            return List.of();
        }
    }

    // 发送消息（如需持久化）
    @PostMapping("/send")
    public ExpertChat sendMessage(@RequestBody ExpertChat message) {
        message.setSendTime(new Date());
        return expertChatRepository.save(message);
    }

    // 获取用户的会话列表（审核通过的预约专家）
    @GetMapping("/sessions/user/{userId}")
    public List<Map<String, Object>> getUserSessions(@PathVariable Long userId) {
        List<ExpertAppointment> list = expertAppointmentRepository.findByUserIdAndStatus(userId, "approved");
        List<Map<String, Object>> result = new java.util.ArrayList<>();
        for (ExpertAppointment appt : list) {
            Map<String, Object> map = new HashMap<>();
            map.put("appointmentId", appt.getId());
            map.put("expertId", appt.getExpertId());
            map.put("userId", appt.getUserId());
            map.put("appointmentTime", appt.getAppointmentTime());
            map.put("description", appt.getDescription());
            map.put("status", appt.getStatus());
            map.put("remark", appt.getRemark());
            Expert expert = expertService.findByUserId(appt.getExpertId());
            map.put("expert", expert);
            result.add(map);
        }
        return result;
    }

    // 获取专家的会话列表（审核通过的预约用户）
    @GetMapping("/sessions/expert/{expertId}")
    public List<Map<String, Object>> getExpertSessions(@PathVariable Long expertId) {
        List<ExpertAppointment> list = expertAppointmentRepository.findByExpertIdAndStatus(expertId, "approved");
        List<Map<String, Object>> result = new java.util.ArrayList<>();
        for (ExpertAppointment appt : list) {
            Map<String, Object> map = new HashMap<>();
            map.put("appointmentId", appt.getId());
            map.put("expertId", appt.getExpertId());
            map.put("userId", appt.getUserId());
            map.put("appointmentTime", appt.getAppointmentTime());
            map.put("description", appt.getDescription());
            map.put("status", appt.getStatus());
            map.put("remark", appt.getRemark());
            User user = userService.getUserById(appt.getUserId().intValue());
            map.put("user", user);
            result.add(map);
        }
        return result;
    }
} 